<template>
  <div class="app-container">
    <!-- 顶部操作栏 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-select v-model="queryParams.classesType" placeholder="请选择班次类型" clearable>
            <el-option v-for="item in shiftTypeOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-input v-model="queryParams.classesName" placeholder="请输入班次名称" clearable @clear="handleQuery"
            @keyup.enter="handleQuery" />
        </el-col>
        <el-col :span="8" class="text-right">
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-card class="mt-2">
      <!-- 操作按钮 -->
      <div class="mb-2">
        <el-button type="primary" @click="showAddDialog">
          <el-icon>
            <Plus />
          </el-icon>新增班次
        </el-button>
        <el-button type="danger" :disabled="!selectedShifts.length" @click="batchDelete">
          <el-icon>
            <Delete />
          </el-icon>批量删除
        </el-button>
      </div>

      <!-- 班次表格 -->
      <el-table :data="shiftList" border v-loading="loading" @selection-change="handleSelectionChange"
        :cell-style="{ textAlign: 'center' }" :header-cell-style="{ textAlign: 'center', fontWeight: 'bold' }">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column prop="classesName" label="班次名称" align="center" />
        <el-table-column label="班次类型" align="center">
          <template #default="{ row }">
            <el-tag :type="getShiftTypeTag(row.classesType)">
              {{ getShiftTypeLabel(row.classesType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="起止时间" align="center">
          <template #default="{ row }">
            {{ row.classesTime }} - {{ row.endTime }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注说明" align="center" />
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteSingleShift(row.departmentId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-2">
        <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑班次对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :close-on-click-modal="false">
      <el-form :model="currentShift" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="班次名称" prop="classesName">
          <el-input v-model="currentShift.classesName" placeholder="请输入班次名称" />
        </el-form-item>
        <el-form-item label="班次类型" prop="classesType">
          <el-select v-model="currentShift.classesType" placeholder="请选择班次类型" style="width: 100%">
            <el-option v-for="item in shiftTypeOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="+item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="classesTime">
          <el-time-picker v-model="currentShift.classesTime" format="HH:mm" value-format="HH:mm" placeholder="选择开始时间"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-time-picker v-model="currentShift.endTime" format="HH:mm" value-format="HH:mm" placeholder="选择结束时间"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="备注说明">
          <el-input v-model="currentShift.remark" type="textarea" :rows="3" placeholder="请输入备注说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import {
  getShiftTypeList,
  getShiftList,
  getShiftDetail,
  addShift,
  updateShift,
  deleteShift
} from '@/api/dispatch/affair/shift_manage'

// 加载状态
const loading = ref(false)

// 班次类型选项
const shiftTypeOptions = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  classesName: '',
  classesType: ''
})

// 班次列表数据
const shiftList = ref([])
const total = ref(0)
const shiftForm = reactive({})

// 当前操作的班次
const currentShift = reactive({
  departmentId: '',
  classesName: '',
  classesType: '',
  classesTime: '',
  endTime: '',
  remark: ''
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('新增班次')
const formRef = ref(null)

// 选中的班次
const selectedShifts = ref([])

// 表单验证规则
const rules = reactive({
  classesName: [
    { required: true, message: '请输入班次名称', trigger: 'blur' }
  ],
  classesType: [
    { required: true, message: '请选择班次类型', trigger: 'change' }
  ],
  classesTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
})

// 初始化数据
const initData = async () => {
  try {
    loading.value = true

    // 获取班次类型列表
    const typeRes = await getShiftTypeList()
    shiftTypeOptions.value = typeRes.data

    // 获取班次列表
    await fetchShiftList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  } finally {
    loading.value = false
  }
}

// 获取班次列表
const fetchShiftList = async () => {
  try {
    loading.value = true
    const res = await getShiftList(queryParams)
    shiftList.value = res.rows
    total.value = res.total
  } catch (error) {
    console.error('获取班次列表失败:', error)
    ElMessage.error('获取班次列表失败')
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchShiftList()
}

// 重置查询条件
const resetQuery = () => {
  queryParams.classesName = ''
  queryParams.classesType = ''
  handleQuery()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchShiftList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchShiftList()
}

// 处理表格选择
const handleSelectionChange = (selection) => {
  selectedShifts.value = selection.map(item => item.departmentId)
}

// 显示新增对话框
const showAddDialog = () => {
  dialogTitle.value = '新增班次'
  resetCurrentShift()
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = async (row) => {
  try {
    loading.value = true
    const res = await getShiftDetail(row.departmentId)
    Object.assign(currentShift, res.data)
    dialogTitle.value = '编辑班次'
    dialogVisible.value = true
  } catch (error) {
    console.error('获取班次详情失败:', error)
    ElMessage.error('获取班次详情失败')
  } finally {
    loading.value = false
  }
}

// 重置当前班次
const resetCurrentShift = () => {
  currentShift.departmentId = ''
  currentShift.classesName = ''
  currentShift.classesType = ''
  currentShift.classesTime = ''
  currentShift.endTime = ''
  currentShift.remark = ''
}

// 确认保存
const confirmSave = async () => {
  try {
    await formRef.value.validate()

    if (dialogTitle.value === '新增班次') {
      await addShift(currentShift)
      ElMessage.success('新增班次成功')
    } else {
      await updateShift(currentShift)
      ElMessage.success('修改班次成功')
    }

    dialogVisible.value = false
    fetchShiftList()
  } catch (error) {
    console.error('保存班次失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 批量删除
const batchDelete = () => {
  if (selectedShifts.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  ElMessageBox.confirm('确认删除选中的班次吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteShift(selectedShifts.value.join(','))
      ElMessage.success('删除成功')
      fetchShiftList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 删除单个班次
const deleteSingleShift = (departmentId) => {
  ElMessageBox.confirm('确认删除该班次吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteShift(departmentId)
      ElMessage.success('删除成功')
      fetchShiftList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 获取班次类型标签
const getShiftTypeTag = (type) => {
  switch (type) {
    case '1': return 'success'
    case '2': return 'warning'
    case '3': return 'danger'
    default: return ''
  }
}

// 获取班次类型标签文本
const getShiftTypeLabel = (type) => {
  const item = shiftTypeOptions.value.find(item => item.dictValue == type)
  return item ? item.dictLabel : type
}

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.text-right {
  text-align: right;
}

.mt-2 {
  margin-top: 20px;
}

.mb-2 {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>